from flask import Flask, render_template, jsonify
from config import Config
from utils.database import init_db
from controllers.auth import auth_bp
from controllers.admin import admin_bp
from controllers.customer import customer_bp
from models.account import Account
from models.transaction import Transaction
from models.user import User
from models.card import Card


def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 初始化数据库
    with app.app_context():
        init_db(app)
    
    # 注册蓝图（重要！）
    app.register_blueprint(auth_bp)
    app.register_blueprint(admin_bp, url_prefix='/admin')  # 可选添加前缀
    app.register_blueprint(customer_bp, url_prefix='/customer')
    
    @app.route('/')
    def home():
        return render_template('index.html')
    
    # 错误处理程序
    @app.errorhandler(404)
    def not_found_error(error):
        return jsonify({'success': False, 'message': '资源未找到'}), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({'success': False, 'message': '服务器内部错误'}), 500
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=False)